import 'dart:io';
import 'dart:typed_data';

import 'package:file_picker/file_picker.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'fit_data_parser.dart';

class FitAnalysisPage extends StatefulWidget {
  const FitAnalysisPage({super.key});

  @override
  State<FitAnalysisPage> createState() => _FitAnalysisPageState();
}

class _FitAnalysisPageState extends State<FitAnalysisPage> {
  bool isLoading = false;
  Map<String, dynamic>? fitAnalysisResult;
  String generatedCsv = '';

  Future<void> _pickFitFileAndAnalyze() async {
    try {
      final result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['fit'],
        allowMultiple: false,
      );

      if (result != null && result.files.isNotEmpty) {
        setState(() {
          isLoading = true;
          fitAnalysisResult = null;
          generatedCsv = ''; // 清空CSV
        });

        Map<String, dynamic> analysisResult;
        
        if (kIsWeb) {
          final bytes = result.files.single.bytes;
          if (bytes != null) {
            analysisResult = await FitDataParser.analyzeFitFileBytes(bytes);
          } else {
            throw Exception('无法读取文件内容');
          }
        } else {
          final filePath = result.files.single.path;
          if (filePath != null) {
            final fitFile = File(filePath);
            analysisResult = await FitDataParser.analyzeFitFile(fitFile);
          } else {
            throw Exception('无法获取文件路径');
          }
        }
        
        final bool isValidFitFile = analysisResult.containsKey('is_valid_fit_file') && analysisResult['is_valid_fit_file'] == true;
        
        if (!isValidFitFile) {
          setState(() {
            fitAnalysisResult = {
              'file_name': analysisResult['file_name'] ?? '未知文件',
              'is_valid_fit_file': false,
              'error_message': '选择的文件不是有效的FIT文件'
            };
          });
        } else {
          setState(() {
            fitAnalysisResult = analysisResult;
          });
        }
      }
    } catch (e) {
      debugPrint('FIT文件分析错误: $e');
      setState(() {
        fitAnalysisResult = {
          'is_valid_fit_file': false,
          'error_message': '文件分析失败，请尝试选择其他FIT文件'
        };
      });
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  Future<void> _convertFitFileToCsv() async {
    try {
      final result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['fit'],
        allowMultiple: false,
      );

      if (result != null && result.files.isNotEmpty) {
        setState(() {
          isLoading = true;
          fitAnalysisResult = null; // 清空旧的分析结果
          generatedCsv = '正在转换...';
        });

        Uint8List? bytes;
        if (kIsWeb) {
          bytes = result.files.single.bytes;
        } else {
          final filePath = result.files.single.path;
          if (filePath != null) {
            bytes = await File(filePath).readAsBytes();
          }
        }

        if (bytes != null) {
          final csvString = await FitDataParser.convertFitToCsvString(bytes);
          setState(() {
            generatedCsv = csvString;
          });
        } else {
          throw Exception('无法读取文件内容');
        }
      }
    } catch (e) {
      setState(() {
        generatedCsv = '转换失败: $e';
      });
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('FIT 数据分析'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // ... FIT 分析部分 ...
            ElevatedButton(onPressed: isLoading ? null : _pickFitFileAndAnalyze, child: isLoading ? const CircularProgressIndicator() : const Text('选择并分析FIT文件')),
            const SizedBox(height: 16),
            ElevatedButton(onPressed: isLoading ? null : _convertFitFileToCsv, child: isLoading ? const CircularProgressIndicator() : const Text('将FIT文件转换为文本(用于分析)')),
            const SizedBox(height: 16),
            
            Text('FIT文件分析结果:', style: Theme.of(context).textTheme.headlineSmall),
            if (isLoading)
              const Padding(
                padding: EdgeInsets.all(32.0),
                child: CircularProgressIndicator(),
              ),
            if (fitAnalysisResult != null)
              if (fitAnalysisResult!['is_valid_fit_file'] == true)
                Column(
                  children: [
                    Text('文件名称: ${fitAnalysisResult!['file_name'] ?? '未知文件'}'),
                    Text('文件大小: ${fitAnalysisResult!['file_size'] ?? 0} 字节'),
                    Text('协议版本: ${fitAnalysisResult!['protocol_version'] ?? 'N/A'}'),
                    Text('配置文件版本: ${fitAnalysisResult!['profile_version'] ?? 'N/A'}'),
                    _buildActivitySummaryCard(),
                    if (_createHeartRateChartData().isNotEmpty)
                      _buildChartCard('心率变化', _createHeartRateChartData(), Colors.red),
                    if (_createSpeedChartData().isNotEmpty)
                      _buildChartCard('速度变化 (km/h)', _createSpeedChartData(), Colors.blue),
                  ],
                )
              else
                Text(
                  fitAnalysisResult!.containsKey('error_message') ? fitAnalysisResult!['error_message'] : '文件分析失败',
                  style: const TextStyle(color: Colors.red),
                ),
            
            const SizedBox(height: 16),
            const Divider(),
            const SizedBox(height: 16),

            if (generatedCsv.isNotEmpty)
              _buildCsvDisplayCard(),
          ],
        ),
      ),
    );
  }

  // 以下都是从旧 MyHomePage 移动过来的辅助方法
  List<FlSpot> _createHeartRateChartData() {
    // ... (代码不变)
    if (fitAnalysisResult == null ||
        fitAnalysisResult!['is_valid_fit_file'] != true ||
        !fitAnalysisResult!.containsKey('records')) {
      return [];
    }
    final records = fitAnalysisResult!['records'] as List<dynamic>;
    final heartRateData = <FlSpot>[];
    for (int i = 0; i < records.length; i++) {
      final record = records[i] as Map<String, dynamic>;
      if (record.containsKey('heart_rate') && record['heart_rate'] != null) {
        heartRateData.add(FlSpot(
          i.toDouble(),
          (record['heart_rate'] as num).toDouble(),
        ));
      }
    }
    return heartRateData;
  }

  List<FlSpot> _createSpeedChartData() {
    // ... (代码不变)
    if (fitAnalysisResult == null ||
        fitAnalysisResult!['is_valid_fit_file'] != true ||
        !fitAnalysisResult!.containsKey('records')) {
      return [];
    }
    final records = fitAnalysisResult!['records'] as List<dynamic>;
    final speedData = <FlSpot>[];
    for (int i = 0; i < records.length; i++) {
      final record = records[i] as Map<String, dynamic>;
      if (record.containsKey('speed') && record['speed'] != null) {
       final speedKmh = (record['speed'] as num).toDouble() * 3.6;
       speedData.add(FlSpot(
         i.toDouble(),
         speedKmh,
       ));
      }
    }
    return speedData;
  }

  Widget _buildActivitySummaryCard() {
    // ... (代码不变)
    if (fitAnalysisResult == null ||
      fitAnalysisResult!['is_valid_fit_file'] != true ||
      !fitAnalysisResult!.containsKey('summary')) {
    return Container();
  }
  final summary = fitAnalysisResult!['summary'] as Map<String, dynamic>;
  
  String formatTime(int totalSeconds) {
    if (totalSeconds < 0) totalSeconds = 0;
    final duration = Duration(seconds: totalSeconds);
    final hours = duration.inHours;
    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);
    return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

  final distanceKm = (summary['total_distance'] ?? 0) / 1000.0;
  final speedKmh = (summary['avg_moving_speed'] ?? 0) * 3.6;
  final maxSpeedKmh = (summary['max_speed'] ?? 0) * 3.6;
  final totalTime = formatTime(summary['total_time_seconds'] ?? 0);
  final movingTime = formatTime(summary['moving_time_seconds'] ?? 0);

  return Card(
    elevation: 4,
    margin: const EdgeInsets.only(top: 16, bottom: 16),
    child: Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('活动摘要', style: Theme.of(context).textTheme.headlineSmall),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildSummaryItem('距离 (km)', distanceKm.toStringAsFixed(2)),
              _buildSummaryItem('移动时间', movingTime),
              _buildSummaryItem('平均速度 (km/h)', speedKmh.toStringAsFixed(1)),
            ],
          ),
          const Divider(height: 24),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildSummaryItem('平均功率 (W)', '${summary['avg_power'] ?? 0}'),
              _buildSummaryItem('最大功率 (W)', '${summary['max_power'] ?? 0}'),
              _buildSummaryItem('平均踏频', '${summary['avg_cadence'] ?? 0}'),
            ],
          ),
          const Divider(height: 24),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildSummaryItem('平均心率', '${summary['avg_heart_rate'] ?? 0} bpm'),
              _buildSummaryItem('最大心率', '${summary['max_heart_rate'] ?? 0} bpm'),
              _buildSummaryItem('总爬升 (m)', (summary['total_ascent'] ?? 0.0).toStringAsFixed(0)),
            ],
          ),
          const Divider(height: 24),
           Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildSummaryItem('卡路里 (kcal)', '${summary['calories'] ?? 0}'),
              _buildSummaryItem('最高速度 (km/h)', maxSpeedKmh.toStringAsFixed(1)),
              _buildSummaryItem('总时间', totalTime),
            ],
          ),
        ],
      ),
    ),
  );
  }

  Widget _buildSummaryItem(String title, String value) {
    // ... (代码不变)
    return Column(
      children: [
        Text(value, style: Theme.of(context).textTheme.headlineSmall),
        Text(title, style: Theme.of(context).textTheme.bodySmall),
      ],
    );
  }

  Widget _buildChartCard(String title, List<FlSpot> data, Color color) {
    return Card(
      elevation: 4,
      margin: const EdgeInsets.only(top: 16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(title, style: Theme.of(context).textTheme.headlineSmall),
            const SizedBox(height: 16),
            SizedBox(
              height: 200,
              child: LineChart(LineChartData(
                lineBarsData: [LineChartBarData(spots: data, isCurved: true, color: color, dotData: const FlDotData(show: false))],
                titlesData: const FlTitlesData(show: true), gridData: const FlGridData(show: true), borderData: FlBorderData(show: true, border: const Border(bottom: BorderSide(), left: BorderSide())), minY: 0,
              )),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCsvDisplayCard() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('FIT 原始数据 (CSV格式):', style: Theme.of(context).textTheme.headlineSmall),
        const SizedBox(height: 8),
        Container(
          height: 400,
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey),
            color: Colors.grey.shade100,
          ),
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: SelectableText(
                  generatedCsv,
                  style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}
